package com.topcent.tioxyc.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.vo.ImageWaterResult;
import com.topcent.tioxyc.pojo.vo.ImageWaterVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 陈百万
 * @date: 2025/9/19 09:23
 * @Description: 海报加水印【数据推送】
 */
@Slf4j
@RestController
public class ImageWatermarkController {

    private static final String DATA_CREATE = "data_create";

    private static final String SECRET = "KPIfb04KeXBOWkj3m9xDqKV9";

    @PostMapping("/imageWatermark")
    public String imageWatermark(@RequestParam("nonce") String nonce,
                               @RequestParam("timestamp") String timestamp,
                               @RequestHeader("x-jdy-signature") String signature,
                               @RequestBody String payload) throws IOException {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleData(payload);

        return "success";
    }

    private void handleData(String payload) throws IOException {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_CREATE.equals(op)) {
            update(data); // 处理图片
        }
    }

    // 处理图片增加水印
    private void update(String data) throws IOException {
        ImageWaterResult result = new ImageWaterResult();
        // 水印地址
        String watermarkPath = "/www/wwwroot/tupian/2025watermark.png"; // 水印图片路径
        ImageWaterVO bean = JSONUtil.toBean(data, ImageWaterVO.class);
        Header[] headers = ConnmeUtils.createHeaders();
        String appId = "64ee9c37ee0a2c0007bc7afc";
        String entryId = "6694810ddb471c31112b395d";
        // 单品海报 url
        List<ImageWaterVO.imgDetail> widget1721008400665 = bean.get_widget_1721008400665();
        // 系列海报 url
        List<ImageWaterVO.imgDetail> widget1721008400666 = bean.get_widget_1721008400666();

        // 随机数
        String transactionId = IdUtil.randomUUID();
        List<String> imgList5 = new ArrayList<>();
        int i = 0;
        for(ImageWaterVO.imgDetail  w5 : widget1721008400665){
            i = i + 1;
            JSONObject uploadToken = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(i);
            String w5Url = w5.getUrl();
            String w5Name = ConnmeUtils.getFileNameWithoutExtension(w5.getName());
            String outputPath = "/www/wwwroot/tupian/" + w5Name + ".jpg";
            addImageTiledWatermark(w5Url, watermarkPath, outputPath, 50, 0.5f, 0.9f); // 增加水印后

            String imageKey = uploadImage(uploadToken.getStr("url"), uploadToken.getStr("token"), new File(outputPath));
            imgList5.add(imageKey);

        }

        List<String> imgList6 = new ArrayList<>();
        for(ImageWaterVO.imgDetail  w6 : widget1721008400666){
            i = i + 1;
            JSONObject uploadToken = getUploadToken(appId, entryId, transactionId, headers).getJSONObject(i);
            String w6Url = w6.getUrl();
            String w6Name = ConnmeUtils.getFileNameWithoutExtension(w6.getName());
            String outputPath = "/www/wwwroot/tupian/" + w6Name + ".jpg";
            addImageTiledWatermark(w6Url, watermarkPath, outputPath, 50, 0.5f, 0.9f); // 增加水印后

            String imageKey = uploadImage(uploadToken.getStr("url"), uploadToken.getStr("token"), new File(outputPath));
            imgList6.add(imageKey);

        }

        result.set_id(bean.get_id());
        result.set_widget_1721008400665(imgList5);
        result.set_widget_1721008400666(imgList6);

        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", appId);
        parameterInster.put("entry_id", entryId);
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", result.get_id());
        parameterInster.put("transaction_id", transactionId);
        result.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(result));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        log.info("海报水印处理的数据{}", jsonSalee);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);

    }


    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + ImageWatermarkController.SECRET + ":" + timestamp);
    }

    /**
     * 给图片添加水印平铺
     * @param targetImageUrl 目标图片URL
     * @param watermarkImageUrl 水印图片URL
     * @param outputPath 输出图片路径
     * gap 水印间距
     * opacity 水印透明度（0-1）
     * @throws IOException
     *//*
    public static void addImageTiledWatermark(String targetImageUrl, String watermarkImageUrl, String outputPath) throws IOException {
        // 读取目标图片和水印图片
        BufferedImage targetImage = ImageIO.read(new URL(targetImageUrl));
        BufferedImage watermarkImage = ImageIO.read(new File(watermarkImageUrl));

        // 创建绘图对象
        Graphics2D g = targetImage.createGraphics();
        // 设置透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));

        int watermarkWidth = watermarkImage.getWidth();
        int watermarkHeight = watermarkImage.getHeight();
        int targetWidth = targetImage.getWidth();
        int targetHeight = targetImage.getHeight();

        // 平铺水印
        for (int y = 0; y < targetHeight; y += watermarkHeight + 50) {
            for (int x = 0; x < targetWidth; x += watermarkWidth + 50) {
                g.drawImage(watermarkImage, x, y, null);
            }
        }

        g.dispose();
        // 保存图片
        ImageIO.write(targetImage, outputPath.substring(outputPath.lastIndexOf(".") + 1), new File(outputPath));
    }*/

    /**
     * 生成token 和 url
     *
     * @param appId
     * @param entryId
     * @param transactionId
     * @return
     */
    public JSONArray getUploadToken(String appId, String entryId, String transactionId, Header[] headers) {
        Map<String, Object> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("entry_id", entryId);
        params.put("transaction_id", transactionId);

        String jsonSale = JSONUtil.toJsonStr(params);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/file/get_upload_token", headers, jsonSale);
        System.out.println("接口返回: token and url ========》》》 " + jdySale);
        // 直接从响应中获取 token_and_url_list
        JSONArray tokenAndUrlList = jdySale.getJSONArray("token_and_url_list");

        if (tokenAndUrlList != null && !tokenAndUrlList.isEmpty()) {
            // 如果数组不为空，获取第一个元素
            return tokenAndUrlList;  // 返回 token 和 url
        } else {
            // 如果数组为空，抛出异常或返回 null
            throw new RuntimeException("No tokens available in token_and_url_list");
        }

    }

    /**
     * 生成 key
     * @param uploadUrl
     * @param token
     * @param imageFile
     * @return
     */
    public String uploadImage(String uploadUrl, String token, File imageFile) {
        String response = HttpRequest.post(uploadUrl)
                .form("token", token)
                .form("file", imageFile, imageFile.getName())  // Upload the image file
                .form("filename", imageFile.getName())  // The filename
                .execute()
                .body();

        JSONObject jsonResponse = JSONUtil.parseObj(response);
        System.out.println("生成key ========++++++》》》 " + jsonResponse);
        return jsonResponse.getStr("key");  // 返回的 key
    }


    /**
     * 给图片添加平铺水印（支持水印按比例缩放）
     * @param targetImageUrl 目标图片路径（本地文件）
     * @param watermarkImageUrl 水印图片路径（本地文件）
     * @param outputPath 输出图片路径
     * @param gap 水印间距（像素）
     * @param opacity 水印透明度（0-1）
     * @param scaleRatio 水印缩放比例（0.1~1.0，1.0为原尺寸，0.5为缩小50%）
     * @throws IOException
     */
    public static void addImageTiledWatermark(String targetImageUrl, String watermarkImageUrl,
                                              String outputPath, int gap, float opacity, float scaleRatio) throws IOException {
        // 1. 读取目标图片和原始水印图片
        BufferedImage targetImage = ImageIO.read(new File(targetImageUrl));
        BufferedImage originalWatermark = ImageIO.read(new File(watermarkImageUrl));

        // 2. 计算缩放后的水印尺寸（保持宽高比）
        int originalWmWidth = originalWatermark.getWidth();
        int originalWmHeight = originalWatermark.getHeight();
        // 缩放后的宽度 = 原宽度 * 缩放比例
        int scaledWmWidth = Math.round(originalWmWidth * scaleRatio);
        // 缩放后的高度 = 原高度 * 缩放比例
        int scaledWmHeight = Math.round(originalWmHeight * scaleRatio);

        // 3. 创建绘图对象，开启抗锯齿（缩放后更清晰）
        Graphics2D g = targetImage.createGraphics();
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, opacity));
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // 抗锯齿

        int targetWidth = targetImage.getWidth();
        int targetHeight = targetImage.getHeight();

        // 4. 平铺缩放后的水印
        for (int y = 0; y < targetHeight; y += scaledWmHeight + gap) {
            for (int x = 0; x < targetWidth; x += scaledWmWidth + gap) {
                // 绘制缩放后的水印：x,y为左上角坐标，scaledWmWidth/scaledWmHeight为缩放后的尺寸
                g.drawImage(originalWatermark, x, y, scaledWmWidth, scaledWmHeight, null);
            }
        }

        // 5. 释放资源并保存
        g.dispose();
        String format = outputPath.substring(outputPath.lastIndexOf(".") + 1);
        ImageIO.write(targetImage, format, new File(outputPath));
    }

}
